import time

from DrissionPage import ChromiumOptions, ChromiumPage
from DrissionPage.common import Actions
import json

path = r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
co = ChromiumOptions().set_paths(browser_path=path)

web_page = ChromiumPage(co)
web_page.listen.start(targets=['web/v1/search/notes','api/sns/web/v1/feed'])
action = Actions(web_page)
web_page.get("https://www.xiaohongshu.com")
search = web_page.ele('xpath://*[@id="search-input"]')
search.input("胃癌")
web_page.ele('xpath://div[@class="search-icon"]').click()
has_more = True
page = 1
data_index = 0
while has_more:
    for i in range(len(web_page.eles('xpath://section'))):
        section_path = f'xpath://section[@data-index="{data_index}"]'
        section = web_page.ele(section_path)
        query_note_xpath = 'xpath://div/div/@class'
        query_note = section.ele(query_note_xpath)
        if query_note is not None and query_note == 'query-note-wrapper':
            data_index += 1
            continue
        else:
            print(f'current section{section.text}')
            section.click()
            pack = web_page.listen.wait()
            print(pack.response.body)
            # 需要增加一个等待元素加载完成
            web_page.ele('xpath://div[@class="close close-mask-dark"]').click()
            data_index += 1
        time.sleep(1.5)